package com.qingxin.sys.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

import com.qingxin.sys.utils.HttpParams.Param;


public class HttpUtil {
	
	
	public static String getString(String urlString, String charset){
		return getWebData(urlString, new HttpParams(false, charset));
	}

	
	public static String getWebData(String urlString, HttpParams httpParams) {
		try {
			if(httpParams == null){
				httpParams = new HttpParams();
			}
			
			String charset = httpParams.getCharset();
			if(StringUtils.isEmpty(charset)){
				charset = "UTF-8";
			}
			
			StringBuilder paramsString = new StringBuilder();
			if(StringUtils.isNotEmpty(httpParams.getData())){
				paramsString.append(httpParams.getData());
			}else if(httpParams.getParams() != null){
				List<Param> params = httpParams.getParams();
				for (int i=0,n=params.size(); i < n; i++) {
					Param param = params.get(i);
					if(i > 0){
						paramsString.append("&");
					}
					paramsString.append(param.getName()).append("=").append(URLEncoder.encode(param.getValue(), charset));
				}
			}
			
			if(paramsString.length()>0 && !httpParams.isPost()){
				if(urlString.indexOf('?') == -1){
					urlString = urlString + '?' + paramsString;
				}else {
					urlString = urlString + '&' + paramsString;
				}
			}
			
			URL url = new URL(urlString);
			HttpURLConnection conn=(HttpURLConnection)url.openConnection();
			
			conn.setRequestMethod(httpParams.isPost() ? "POST" : "GET");
			
			if(httpParams.getHeaders() != null){
				List<Param> headers = httpParams.getHeaders();
				for(HttpParams.Param header : headers){
					conn.setRequestProperty(header.getName(), header.getValue());
				}
			}
			
			conn.setDoInput(true);
			
			if(paramsString.length()>0 && httpParams.isPost()){
				conn.setDoOutput(true);
				PrintWriter pw=new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), charset));
				pw.print(paramsString.toString());
				pw.close();
			}
			
			BufferedReader reader=new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
			StringBuffer buf = new StringBuffer();
			char[] cbuf = new char[128];
			int n = -1;
			while((n=reader.read(cbuf))!=-1){
				buf.append(cbuf, 0, n);
			}
			reader.close();
			
			return buf.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
}
